﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.IO;
using Microsoft.Win32;

namespace ITunesSolver.Helpers
{
    public class FileHelper
    {
        public FileHelper()
        {
        }

        public static string SelectFile(string fileName)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.FileName = fileName;
            //openFileDialog.FileName = "iTunes Music Library.xml";
            openFileDialog.Filter = "\"XML files|*.xml|All files|*.*";
            openFileDialog.Title = "Select your iTunes library file...";

            bool? res = openFileDialog.ShowDialog();

            if (res.HasValue && res == true)
            {
                fileName = openFileDialog.FileName;

                return fileName;
            }


            return string.Empty;
        }

        public static byte[] ReadFile(string filePath)
        {
            byte[] buffer;
            FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            try
            {
                int length = (int)fileStream.Length;  // get file length
                buffer = new byte[length];            // create buffer
                int count;                            // actual number of bytes read
                int sum = 0;                          // total number of bytes read

                // read until Read method returns 0 (end of the stream has been reached)
                while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                    sum += count;  // sum is a buffer offset for next reading
            }
            finally
            {
                fileStream.Close();
            }
            return buffer;
        }

        public static FileStream CreateFileStream(string filePath)
        {
            FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            return fileStream;
        }

        public static FileInfo GetFileInfo(string filePath)
        {
            return new FileInfo(filePath);
        }

        internal static string CreateOutputPath(FileInfo fi)
        {
            DateTime now = DateTime.Now;
            string fullName = fi.Name;
            string ext = fi.Extension;
            string fileName = fi.Name.Replace(ext, "");
            fileName = fileName + now.ToString("yyyyMMddhhmmss") + ext;

            return fi.DirectoryName + "\\" + fileName;
        }
    }
}
